package com.unitd.frame.springweb.plugins.velocity.directive;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;

/**
 * @desc velocity的指令管理工具类
 * @filename DirectiveUtil.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/2
 */
public class DirectiveUtil {
	static String BLOCK = "__vm_override__";
	static String OVERRIDE_CURRENT_NODE = "__vm_current_override_node__";

	public DirectiveUtil() {
	}

	static String getOverrideVariableName(String name) {
		return BLOCK + name;
	}

	static String getRequiredArgument(InternalContextAdapter context, Node node, int argumentIndex, String directive) throws ParseErrorException {
		SimpleNode sn_value = (SimpleNode) node.jjtGetChild(argumentIndex);
		if (sn_value == null) {
			throw new ParseErrorException("required argument is null with directive:#" + directive + "(),argumentIndex=" + argumentIndex);
		} else {
			String value = (String) sn_value.value(context);
			if (value == null) {
				throw new ParseErrorException("required argument is null with directive:#" + directive + "(),argumentIndex=" + argumentIndex);
			} else {
				return value;
			}
		}
	}

	public static void setParentForTop(OverrideDirective.OverrideNodeWrapper topParentNode, OverrideDirective.OverrideNodeWrapper node) {
		OverrideDirective.OverrideNodeWrapper top;
		for (top = node; top.parentNode != null; top = top.parentNode) {
			;
		}

		top.parentNode = topParentNode;
	}
}